package cvsexample8;

public class BasicExceptionHandling {
	
	/* private global variable */
	private static int numMethodCalls = 0;
	
	/* methodA to call methodB and increment/decrement the global variable */
	public static void methodA() {
		System.out.println("Enter methodA: Number of method calls = " + (++numMethodCalls));
		methodB();
		System.out.println("Exit methodA: Number of method calls = " + numMethodCalls--);
	}
	
	/* methodB to call methodC and increment/decrement the global variable */
	public static void methodB() {
		System.out.println("Enter methodB: Number of method calls = " + (++numMethodCalls));
		methodC();
		System.out.println("Exit methodB: Number of method calls = " + numMethodCalls--);
	}
	
	/* methodC to call methodD and increment/decrement the global variable */
	public static void methodC() {
		System.out.println("Enter methodC: Number of method calls = " + (++numMethodCalls));
		methodD();
		System.out.println("Exit methodC: Number of method calls = " + numMethodCalls--);
	}
	
	/* methodD to increment/decrement the global variable */
	@SuppressWarnings("null")
	public static void methodD() {
		System.out.println("Enter methodD: Number of method calls = " + (++numMethodCalls));
		
		/* Create a reference to a String object, setting it = null
		 * attempt to use the String length() method before it has been instantiated! 
		 */
		int lenString = 0;
		String strTest = null;
		
		/* Use a try-catch-finally to handle the exception (NullPointerException) */
		try {
			System.out.println("methodD: Enter try block");
			System.out.println("methodD: About to use length() on " + strTest);
			lenString = strTest.length();
			System.out.println("methodD: Exit try block");
		} catch (NullPointerException ex) {
			System.out.println("methodD: Enter catch block");
			/* Output the stack trace to help debug the problem */
			ex.printStackTrace();
			System.out.println("methodD: Exit catch block");
		} finally {
			System.out.println("methodD: Enter finally block");
			System.out.println("methodD: lenString = " + lenString);
			System.out.println("methodD: Exit finally block");
		}
		System.out.println("Exit methodD: Number of method calls = " + numMethodCalls--);
	}

	public static void main(String[] args) {
		
		/* Output a start message to the console */
		System.out.println("Exercise 8 - Exception Handling started");
		
		System.out.println("Enter main method");
		methodA();
		System.out.println("Exit main method");
		
		/* Output a completed message to the console */
		System.out.println("Exercise 8 - Exception Handling completed");
	}
}
